<template>
  <div class="app-container">

    <el-steps :active="2" finish-status="success" simple style="margin: 20px 0">
      <el-step title="编辑课程基本信息"></el-step>
      <el-step title="编辑课程大纲"></el-step>
      <el-step title="发布课程"></el-step>
    </el-steps>

    <el-button type="danger" @click="openChapterDialog1">添加章节</el-button>

    <!-- 章节表单-->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form>
        <el-form-item label="章节标题" label-width="80px">
          <el-input v-model="chapter.title" clearable placeholder="章节标题"></el-input>
        </el-form-item>
        <el-form-item label="章节排序" label-width="80px">
          <el-input-number v-model="chapter.sort" :min="0" placeholder="章节排序" controls-position="right"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="sure">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 小节表单-->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisibleForVideo">
      <el-form>
        <!-- 章节id-->
        <input type="hidden" :value="chapter.id">
        <el-form-item label="当前章节" label-width="80px">
          <el-input v-model="chapter.title" disabled placeholder="章节标题"></el-input>
        </el-form-item>
        <el-form-item label="小节标题" label-width="80px">
          <el-input v-model="video.title" clearable placeholder="小节标题"></el-input>
        </el-form-item>
        <el-form-item label="小节排序" label-width="80px">
          <el-input-number v-model="video.sort" :min="0" placeholder="小节排序" controls-position="right"></el-input-number>
        </el-form-item>
        <el-form-item label="视频上传" label-width="80px">
          <el-upload
              :on-success="uploadVideoSuccess"
              :before-remove="beforeVideoRemove"
              :file-list="fileList"
              :action="BASE_API+'/video/addVideo'"
              :limit="1"
              class="upload">
          <el-button size="small" type="primary">上传视频</el-button>
          <el-tooltip placement="right-end">
            <div slot="content">最大支持 100MB<br>
                支持3GP、ASF、AVI、DAT、DV、FLV、F4V、<br>
                GIF、M2T、M4V、MJ2、MJPEG、MKV、MOV、MP4、<br>
                MPE、MPG、MPEG、MTS、OGG、QT、RM、RMVB、<br>
                SWF、TS、VOB、WMV、WEBM 等视频格式上传</div>
            <i class="el-icon-question"/>
          </el-tooltip>
          </el-upload>
        </el-form-item>
        <el-form-item label="视频免费" label-width="80px">
          <el-radio v-model="video.isFree" :label="0" border>收费</el-radio>
          <el-radio v-model="video.isFree" :label="1" border>免费</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancleForVideo">取 消</el-button>
        <el-button type="primary" @click="sureForVideo">确 定</el-button>
      </div>
    </el-dialog>

    <el-input v-model="filterText" placeholder="请输入搜索关键字" style="margin: 30px 0;" />

    <el-tree
      :data="data"
      node-key="id"
      :filter-node-method="filterNode"
      :expand-on-click-node="false"
      ref="tree">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span style="display: inline-block;width: 400px;">{{ data.title }}</span>
        <span v-if="data.flag==0">
          <el-button
            type="success"
            size="mini"
            @click="() => openChapterDialog3(node, data)">
            新增小节
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click="() => openChapterDialog2(node, data)">
            编辑章节
          </el-button>
          <el-button
            type="danger"
            size="mini"
            @click="() => removeChapter(node, data)">
            移除章节
          </el-button>
        </span>
        <span v-else style="margin-left: 30px;">
          <el-button
            type="primary"
            size="mini"
            @click="() => openChapterDialog4(node, data)">
            编辑小节
          </el-button>
          <el-button
            type="warning"
            size="mini"
            @click="() => removeVideo(node, data)">
            移除小节
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-form label-width="120px" style="margin-top: 50px;">
      <el-form-item>
        <el-button type="primary" @click="previous" :disabled="btnStatus">上一步</el-button>
        <el-button type="primary" @click="next" :disabled="btnStatus">保存并下一步</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script>

  import course from '@/api/course'

  // 导入js-cookie
  import cookie from 'js-cookie'

  export default {
    data() {
      return {
        "btnStatus": false,
        "courseId": "",

        filterText: '',
        data: [],
        defaultProps: {
          children: 'children',
          label: 'title'
        },
        chapter: {
          "id": "", // 章节id，用于区分新增和修改
          "title": "",
          "sort": 0
        },
        // 小节对象
        "video": {
          "id": "",
          "title": "",
          "sort": 0,
          "isFree": 0,
          // 视频id
          "videoSourceId": "",
          // 视频名称
          "videoOriginalName": "",
          // 视频大小
          "size": "",
          // 视频时长
          "duration": "",
          // 视频状态
          "status": ""
        },

        // 获取dev.env.js里面地址
        BASE_API: process.env.BASE_API,
        // 上传视频列表
        fileList: [],

        // 弹窗标题
        "dialogTitle": "",
        // 添加章节对话框默认关闭
        "dialogFormVisible": false,
        // 小节弹窗状态
        "dialogFormVisibleForVideo": false
      }
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val)
      }
    },
    created() {
      // 获取第一步传值的课程id
      if(this.$route.params && this.$route.params.id) {
        this.courseId=this.$route.params.id;
        // 查询章节和小节信息
        this.getAllChapterAndVideo(this.$route.params.id);
      }
    },
    methods: {
      // 回退到"课程详情页面"
      previous() {
        // 取出cookie中的课程id
        let c=JSON.parse(unescape(cookie.get("course")));
        this.$router.push({"path": `/course/info/${this.courseId}`});
        cookie.set("course", escape(JSON.stringify(c)));
      },
      // 跳转到"发布课程"页面
      next() {
        // 如果课程章节和小节为空，则提示
        if(this.data.length==0) {
          this.$message.error("未添加任何章节或小节信息");
          return ;
        }
        this.$router.push({"path": `/course/publish/${this.courseId}`});
      },

      // 获取指定课程id的章节和小节信息
      getAllChapterAndVideo(courseId) {
        course.getAllChapterAndVideo(courseId)
          .then(res => {
            // 为章节小节数据赋值
            this.data=res.data.chapters;
          }).catch(err => {
            this.$message.error(err.message);
          });
      },
      // 章节信息检索
      filterNode(value, data) {
        if (!value) return true
        return data.title.toLowerCase().indexOf(value.toLowerCase()) !== -1
      },

      // 打开添加章节对话框
      openChapterDialog1() {
        this.dialogTitle="添加章节";
        this.chapter.title="";
        this.chapter.sort=0;
        this.chapter.id="";
        this.dialogFormVisible=true;
      },
      // 打开修改章节对话框
      openChapterDialog2(node, data) {
        this.dialogTitle="修改章节";
        this.chapter.title=data.title;
        this.chapter.sort=data.sort;
        this.chapter.id=data.id;
        this.dialogFormVisible=true;
      },
      // 打开新增小节对话框
      openChapterDialog3(node,data) {
        this.dialogTitle="新增小节";
        this.chapter.id=data.id;
        this.chapter.title=data.title;
        this.video={};
        this.video.sort=0;
        this.$set(this.video,'isFree',0);
        this.dialogFormVisibleForVideo=true;
      },
      // 打开修改小节对话框
      openChapterDialog4(node,data) {
        this.dialogTitle="修改小节";
        this.chapter.id=node.parent.data.id;
        this.chapter.title=node.parent.data.title;
        this.video.id=data.id;
        this.video.title=data.title;
        this.video.sort=data.sort;
        this.video.isFree=data.isFree;
        this.dialogFormVisibleForVideo=true;
      },

      // 关闭对话框
      cancle() {
        this.dialogFormVisible=false;
      },
      // 关闭小节对话框
      cancleForVideo() {
        this.fileList=[];
        this.dialogFormVisibleForVideo=false;
      },
      // 提交对话框中的数据
      sure() {
        // 参数校验
        if(!this.chapter.title) {
          this.$message.error("章节标题不能为空");
          return ;
        }
        if(this.chapter.sort < 0) {
          this.$message.error("章节排序非法");
          return ;
        }
        // 判断是新增还是修改
        // 修改
        if(this.chapter.id) {
          this.updateChapter();
          return ;
        }
        // 新增
        this.addChapter();
      },
      // 提交小节对话框中的数据
      sureForVideo() {
        // 参数校验
        if(!this.chapter.id) {
          this.$message.error("章节id获取失败");
          return ;
        }
        if(!this.chapter.title) {
          this.$message.error("章节标题获取失败");
          return ;
        }
        if(!this.video.title) {
          this.$message.error("小节标题不能为空");
          return ;
        }
        if(this.video.sort < 0) {
          this.$message.error("小节排序非法");
          return ;
        }
        if(!(this.video.isFree==0 || this.video.isFree==1)) {
          this.$message.error("视频免费状态非法");
          return ;
        }
        if(!this.video.videoSourceId) {
          this.$message.error("视频id不能为空");
          return ;
        }
        if(!this.video.videoOriginalName) {
          this.$message.error("视频名称不能为空");
          return ;
        }
        // 调用接口获取其他视频信息
        course.selectVideoInfo(this.video.videoSourceId)
          .then(res => {
            this.video.size=res.data.size;
            this.video.duration=res.data.duration;
            this.video.status=res.data.status;
            if(this.video.size<=0) {
              this.$message.error("视频大小有误");
              return ;
            }
            if(this.video.duration<=0) {
              this.$message.error("视频时长不能为空");
              return ;
            }
            if(!this.video.status) {
              this.$message.error("视频状态不能为空");
              return ;
            }
            // 判断是修改还是新增
            if(this.video.id) {
              // 修改
              this.updateVideo();
              return ;
            }
            // 新增
            this.addVideo();
          }).catch(err => {
            this.$message.error("视频详情信息查询失败");
          });
      },
      // 新增章节
      addChapter() {
        // 校验章节是否已存在
        this.data.forEach((obj,index) => {
          if(obj.title==this.chapter.title) {
            this.$message.error("章节名已存在");
            throw "终止forEach";
          }
          if(obj.sort==this.chapter.sort) {
            this.$message.error("排序已存在");
            throw "终止forEach";
          }
        });
        // 执行新增操作
        // 构造章节实体对象
        let c={
          "courseId": this.courseId,
          "title": this.chapter.title,
          "sort": this.chapter.sort
        };
        course.addChapter(c)
          .then(res => {
            this.$message({
              type: 'success',
              message: res.message,
            });
            // 关闭对话框
            this.dialogFormVisible=false;
            // 重新获取章节和小节数据
            this.getAllChapterAndVideo(this.courseId);
            // 清空章节表单数据
            this.chapter.title="";
            this.chapter.sort=0;
            this.chapter.id="";
          }).catch(err => {
            this.$message.error(err.message);
          });
      },
      // 修改章节
      updateChapter() {
        // 校验章节id是否为空
        if(!this.chapter.id) {
          this.$message.error("章节id获取失败");
          return ;
        }
        // 校验章节是否已存在
        this.data.forEach((obj,index) => {
          if(obj.title==this.chapter.title && obj.id!=this.chapter.id) {
            this.$message.error("章节名已存在");
            throw "终止forEach";
          }
          if(obj.sort==this.chapter.sort && obj.id!=this.chapter.id) {
            this.$message.error("排序已存在");
            throw "终止forEach";
          }
        });
        // 执行修改操作
        // 构造章节实体对象
        let c={
          "id": this.chapter.id,
          "courseId": this.courseId,
          "title": this.chapter.title,
          "sort": this.chapter.sort
        };
        course.updateChapter(c)
          .then(res => {
            this.$message({
              type: 'success',
              message: res.message,
            });
            // 关闭对话框
            this.dialogFormVisible=false;
            // 重新获取章节和小节数据
            this.getAllChapterAndVideo(this.courseId);
            // 清空章节表单数据
            this.chapter.title="";
            this.chapter.sort=0;
            this.chapter.id="";
          }).catch(err => {
            this.$message.error(err.message);
          });
      },
      // 删除章节
      removeChapter(node,data) {
        // 校验参数
        if(!data.id) {
          this.$message.error("章节id不能为空");
          return ;
        }
        this.$confirm(`确定删除章节: <span style="color: orange;">${data.title}</span> ?`, '章节删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          'dangerouslyUseHTMLString': true
        }).then(() => {
          course.deleteChapter(data.id)
            .then(res => {
              this.$message({
                type: 'success',
                message: res.message,
              });
              // 重新加载数据
              this.getAllChapterAndVideo(this.courseId);
            }).catch(err => {
              this.$message.error(err.message);
            });
        }).catch(() => {
          this.$message({
            type: 'success',
            message: "取消删除",
          });
        });
      },
      // 添加小节
      addVideo() {
        // 校验小节是否已存在
        for(let i=0;i<this.data.length;i++) {
          // 遍历二级的小节数据
          if(this.data[i].children) {
            for(let j=0;j<this.data[i].children.length;j++) {
              // 章节相同时，小节不能相同
              if(this.data[i].title==this.chapter.title && this.data[i].children[j].title==this.video.title) {
                this.$message.error("小节名已存在");
                return ;
              }
              if(this.data[i].title==this.chapter.title && this.data[i].children[j].sort==this.video.sort) {
                this.$message.error("排序已存在");
                return ;
              }
            }
          }
        }
        // 执行新增操作
        // 构造小节实体对象
        let v={
          "courseId": this.courseId,
          "chapterId": this.chapter.id,
          "title": this.video.title,
          "sort": this.video.sort,
          "isFree": this.video.isFree,
          "videoSourceId": this.video.videoSourceId,
          "videoOriginalName": this.video.videoOriginalName,
          "size": this.video.size,
          "duration": this.video.duration,
          "status": this.video.status
        };
        course.addVideo(v)
          .then(res => {
            this.$message({
              type: 'success',
              message: res.message,
            });
            // 关闭对话框
            this.dialogFormVisibleForVideo=false;
            // 重新获取章节和小节数据
            this.getAllChapterAndVideo(this.courseId);
            // 清空小节表单数据
            this.chapter.id="";
            this.chapter.title="";
            this.video={};
            this.video.sort=0;
            this.video.isFree=0;
            this.fileList=[];
          }).catch(err => {
            this.$message.error(err.message);
          });
      },
      // 修改小节信息
      updateVideo() {
        // 校验小节id是否为空
        if(!this.video.id) {
          this.$message.error("小节id获取失败");
          return ;
        }
        // 校验小节是否已存在
        for(let i=0;i<this.data.length;i++) {
          // 遍历二级的小节数据
          if(this.data[i].children) {
            for(let j=0;j<this.data[i].children.length;j++) {
              // 章节相同时，除自己以外，小节不能相同
              if(this.data[i].title==this.chapter.title && this.data[i].children[j].id!=this.video.id && this.data[i].children[j].title==this.video.title) {
                this.$message.error("小节名已存在");
                return ;
              }
              if(this.data[i].title==this.chapter.title && this.data[i].children[j].id!=this.video.id && this.data[i].children[j].sort==this.video.sort) {
                this.$message.error("排序已存在");
                return ;
              }
            }
          }
        }
        // 执行修改操作
        // 构造小节对象
        let v={
          "id": this.video.id,
          "courseId": this.courseId,
          "chapterId": this.chapter.id,
          "title": this.video.title,
          "sort": this.video.sort,
          "isFree": this.video.isFree,
          "videoSourceId": this.video.videoSourceId,
          "videoOriginalName": this.video.videoOriginalName,
          "size": this.video.size,
          "duration": this.video.duration,
          "status": this.video.status
        };
        course.updateVideo(v)
          .then(res => {
            this.$message({
              type: 'success',
              message: res.message,
            });
            // 关闭对话框
            this.dialogFormVisibleForVideo=false;
            // 重新获取章节和小节数据
            this.getAllChapterAndVideo(this.courseId);
            // 清空小节表单数据
            this.chapter.id="";
            this.chapter.title="";
            this.video={};
            this.video.sort=0;
            this.video.isFree=0;
            this.fileList=[];
          }).catch(err => {
            this.$message.error(err.message);
          });
      },
      // 删除小节信息
      removeVideo(node,data) {
        // 校验参数
        if(!data.id) {
          this.$message.error("小节id不能为空");
          return ;
        }
        this.$confirm(`确定删除小节: <span style="color: orange;">${data.title}</span> ?`, '小节删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          'dangerouslyUseHTMLString': true
        }).then(() => {
          course.deleteVideo(data.id)
            .then(res => {
              this.$message({
                type: 'success',
                message: res.message,
              });
              // 重新加载数据
              this.getAllChapterAndVideo(this.courseId);
            }).catch(err => {
              this.$message.error(err.message);
            });
        }).catch(() => {
          this.$message({
            type: 'success',
            message: "取消删除",
          });
        });
      },
      // 上传视频成功回调方法
      uploadVideoSuccess(res,file,fileList) {
        this.video.videoSourceId=res.data.videoId;
        this.video.videoOriginalName=res.data.title;
        // 提示上传成功
        this.$message({
          type: 'success',
          message: res.message,
        });
      },
      // 视频移除
      beforeVideoRemove(file,fileList) {
        // 执行删除
        course.deleteVideoByVideoId(this.video.videoSourceId)
          .then(res => {
            // 清除数据
            this.video.videoSourceId="";
            this.video.videoOriginalName="";
            this.$message({
              type: 'success',
              message: res.message,
            });
          }).catch(err => {
            this.$message.error(err.message);
          });
      }
    }
  }

</script>

<style>

  .el-tree-node {
    margin: 10px 0;
  }

</style>
